<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;

class Admin extends Model
{
    use HasFactory;

    /**
     * 数据表名
     *
     * @var string
     */
    protected $table = 'admins';
    
    /**
     * 可批量赋值的属性
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'username',
        'name',
        'password',
        'is_active',
        'last_login_at',
    ];

    /**
     * 自动类型转换
     *
     * @var array<string, string>
     */
    protected $casts = [
        'is_active' => 'boolean',
        'last_login_at' => 'datetime',
    ];

    /**
     * 隐藏的属性
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
    ];

    /**
     * 自动加密密码
     */
    public function setPasswordAttribute($value)
    {
        // 如果密码已经哈希化或者为空，则不再处理
        if (!$value || (strlen($value) >= 60 && preg_match('/^\$[0-9a-zA-Z]{2}\$/', $value))) {
            $this->attributes['password'] = $value;
            return;
        }

        $this->attributes['password'] = Hash::make($value);
    }
}
